package cn.ex.ymcc.service.impl;

import cn.ex.ymcc.domain.KillActivity;
import cn.ex.ymcc.domain.KillCourse;
import cn.ex.ymcc.mapper.KillActivityMapper;
import cn.ex.ymcc.service.IKillActivityService;
import cn.ex.ymcc.service.IKillCourseService;
import cn.ex.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  秒杀活动的业务实现
 * </p>
 *
 *
 */
@Service
@Slf4j
public class KillActivityServiceImpl extends ServiceImpl<KillActivityMapper, KillActivity> implements IKillActivityService {
    @Autowired
    private IKillCourseService killCourseService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public void publish(Long activityId) {
        //查询出秒杀活动对应的课程
        List<KillCourse> killCourses = queryActivityCourse(activityId);
        KillCourse killCourse = killCourses.get(0);
        //校验时间是否满足，满足条件才发布活动
        Date startTime = killCourse.getStartTime();
        Date now = new Date();
        //当前时间在结束时间之后则不满足
        boolean before = now.before(killCourse.getEndTime());
        AssertUtil.isTrue(before,"发布失败！！");
        killCourses.forEach(course->{
            //redis设置每个课程的信号量
            String key = activityId +":"+course.getId();
            RSemaphore semaphore = redissonClient.getSemaphore(key);
            //设置库存 （许可数量）
            boolean setPermits = semaphore.trySetPermits(course.getKillCount());
            //设置成功，保存redis
            if(setPermits){

                redisTemplate.opsForHash().put("activity:"+activityId,course.getId().toString(),course);
                //修改秒杀课程状态
                course.setPublishTime(now);
                course.setPublishStatus(1);
                killCourseService.updateById(course);
            }else{
                //做兜底方案，通知管理人员
            }
        });
        //修改状态
        KillActivity killActivity = selectById(activityId);
        killActivity.setPublishTime(now);
        killActivity.setPublishStatus(1);
        updateById(killActivity);
    }

    public List<KillCourse> queryActivityCourse(Long activityId){
        Wrapper<KillCourse> query = new EntityWrapper<>();
        query.eq("activity_id",activityId);
        return killCourseService.selectList(query);
    }
}
